package com.itbaizhan.dubbo;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itbaizhan.common.BaseResponse;
import com.itbaizhan.entity.TAccount;
import com.itbaizhan.mapper.TAccountMapper;
import com.itbaizhan.service.ITAccountService;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 账户业务层
 */

@DubboService
public class ITAccountServiceImpl implements ITAccountService {

    @Autowired
    private TAccountMapper tAccountMapper;

    /**
     * 从账户扣减余额
     * @param userId 用户id
     * @param money 金额
     * @return
     */
    @Override
    public BaseResponse deduct(String userId, Integer money) {
        // 查询用户余额
        LambdaQueryWrapper<TAccount>  tAccountLambdaQueryWrapper = new LambdaQueryWrapper();
        tAccountLambdaQueryWrapper.eq(TAccount::getUserId,userId);
        TAccount tAccount = tAccountMapper.selectOne(tAccountLambdaQueryWrapper);
        if (tAccount == null ){
            return BaseResponse.error("用户不存在");
        }
        if (tAccount.getMoney() <  money){
            return BaseResponse.error("余额不足");
        }

        // 更新余额
        tAccount.setMoney(tAccount.getMoney() - money);
        int i = tAccountMapper.updateById(tAccount);
        if (i > 0){
            return BaseResponse.success();
        }
        return BaseResponse.error("服务异常");
    }

}
